﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Runtime.InteropServices;
using System.Security.Cryptography;
namespace BiaoQianPrint.Tools
{
    class CZCM
    {
        [DllImport("MicrosoftOfficeModel.dll", CallingConvention = CallingConvention.Cdecl)]
        static extern byte getOterCode(string pInStr, ref StringBuilder sReturn);//StringBuilder cPath, StringBuilder cTaskID);//IntPtr pPath); 

        [DllImport("MicrosoftOfficeModel.dll", CallingConvention = CallingConvention.Cdecl)]
        static extern byte getMoshinaCode(ref StringBuilder sReturn);

        public string strMidle = "";
        public string strMidle2 = "";

        public string testGetJQM()
        {
            StringBuilder s = new StringBuilder(200); 
            if (getMoshinaCode(ref s) == 1)
            {
                return s.ToString();
            }
            return "";
        }

        public string returnZCM(string pJiQiMa)
        {
            StringBuilder sResult = new StringBuilder(255);
            getOterCode(pJiQiMa, ref sResult);//先用MFC简单移位处理。防止C#被破解。
            strMidle = sResult.ToString();
            return ComputeZCM(sResult.ToString());//C#再次进行简单移位处理。防止对方调用MFC dll后就，不用破解c#就能得到注册码。
        }
        private string ComputeZCM(string mJiQiMa)
        {
            //第4位和第8位交换
            swapString(4, 8, ref mJiQiMa);
            //第15  19位
            swapString(15, 19, ref mJiQiMa);

            for (int i = 0; i < 27; i++)
            {
                swapString(i, 28 + i, ref mJiQiMa);
            }
            for (int i = 32; i < 63; i++)
            {
                swapString(i, 32 + i, ref mJiQiMa);
            }

            strMidle2 = mJiQiMa;
            return GetMD5(mJiQiMa);
            
        }

        private void swapString(int No1, int No2, ref string pStr)
        {
            string s1 = pStr.Substring(No1, 1);
            string s2 = pStr.Substring(No2, 1);

            string newStr1= pStr.Remove(No1, 1);
            newStr1 = newStr1.Insert(No1, s2);
            string newStr2 = newStr1.Remove(No2, 1);
            newStr2=newStr2.Insert(No2, s1);

            pStr = newStr2;
        }
        //md5是一个摘要算法，理论上说是不可逆的。
        private string GetMD5(string str)
        {
            byte[] strBytes = Encoding.UTF8.GetBytes(str);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] outputBytes = md5.ComputeHash(strBytes);
            return BitConverter.ToString(outputBytes).Replace("-", "");
        }
    }
}
